//
//  SearchViewController.m
//  BaseFrame
//
//  Created by 孟学浩 on 2017/4/5.
//  Copyright © 2017年 com.mxh. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchTypeView.h"
#import "SearchGoodsViewController.h"
#import "SearchShopViewController.h"

@interface SearchViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) UIView *headerView;
@property (nonatomic,strong) UIView *footerView;
@property (nonatomic,strong) UITextField *searchTextField;

@property (nonatomic,strong) NSArray *dataArray;
@property (nonatomic,strong) NSDictionary *dataDictionary;

@property (nonatomic,assign) NSUInteger type;

@end

//网络
@implementation SearchViewController (NetWorking)



@end

//UI
@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataArray = [UserModel sharedInstanced].searchGoodsArray;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"search"] style:0 target:self action:@selector(searchEvent)];
    self.type = 0;
    self.navigationItem.titleView = ({
        _searchTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 7, SCREEN_WIDTH, 30)];
        _searchTextField.layer.borderWidth = .5;
        _searchTextField.layer.borderColor = [UIColor whiteColor].CGColor;
        _searchTextField.layer.masksToBounds = YES;
        _searchTextField.layer.cornerRadius = 15;
        _searchTextField.placeholder = @"搜索商品或店铺名称";
        _searchTextField.textColor = [UIColor whiteColor];
        _searchTextField.font = DEF_FontSize_12;
        _searchTextField.leftViewMode = UITextFieldViewModeAlways;
        _searchTextField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
        [_searchTextField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
        [_searchTextField becomeFirstResponder];
        _searchTextField.leftViewMode = UITextFieldViewModeAlways;
        _searchTextField.leftView = ({
            
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 70, 30)];
            
            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 55, 30)];
            [btn setTitle:@"商品" forState:UIControlStateNormal];
            btn.titleLabel.font = DEF_FontSize_10;
            [btn addTarget:self action:@selector(typeSelectEvent:) forControlEvents:UIControlEventTouchUpInside];
            btn.layer.masksToBounds = YES;
            
            CALayer *layer = [CALayer layer];
            layer.frame = CGRectMake(55, 0, .5, 30);
            layer.backgroundColor = [UIColor whiteColor].CGColor;
            
            UIView *smallView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
            smallView.center = CGPointMake(55, 30);
            smallView.backgroundColor = [UIColor whiteColor];
            smallView.transform = CGAffineTransformMakeRotation(M_PI*.25);
            
            [btn addSubview:smallView];
            [view.layer addSublayer:layer];
            [view addSubview:btn];
            view;
        });
        _searchTextField;
    });
    [self.view addSubview:self.tableView];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    switch (self.type) {
        case 0:{
            self.dataArray = [UserModel sharedInstanced].searchGoodsArray;
            [self.tableView reloadData];
        }break;
        case 1:{
            self.dataArray = [UserModel sharedInstanced].searchShopArray;
            [self.tableView reloadData];
        }break;
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

#pragma mark - Event

- (void)typeSelectEvent:(UIButton *)sender{
    SearchTypeView *view = [[SearchTypeView alloc] initWithFrame:CGRectMake(70, 57, 50, 60)];
    [view show];
    view.typeSelectHandle = ^(NSUInteger index) {
        [sender setTitle:@[@"商品",@"店铺"][index] forState:UIControlStateNormal];
        self.type = index;
        switch (self.type) {
            case 0:{
                self.dataArray = [UserModel sharedInstanced].searchGoodsArray;
                [self.tableView reloadData];
            }break;
            case 1:{
                self.dataArray = [UserModel sharedInstanced].searchShopArray;
                [self.tableView reloadData];
            }break;
        }
    };
}

- (void)searchEvent{
    if ([self.searchTextField.text isEqualToString:@""]) {
        ShowMessage(@"请输入要搜索的商品名或店铺名");
        return;
    }
    switch (self.type) {
        case 0:{
            [UserModel addSearchGoodsHistory:self.searchTextField.text];
            SearchGoodsViewController *vc = [SearchGoodsViewController new];
            vc.name = self.searchTextField.text;
            [self.navigationController pushViewController:vc animated:YES];
        }break;
        case 1:{
            [UserModel addSearchShopHistory:self.searchTextField.text];
            SearchShopViewController *vc = [SearchShopViewController new];
             vc.name = self.searchTextField.text;
            [self.navigationController pushViewController:vc animated:YES];
        }break;
    }
}

#pragma mark - UITableViewDelegate & UITableViewDataSource

//左划效果
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(8_0){
    UITableViewRowAction *action1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        //                [tableView beginUpdates];
        //有时候不加注释的方法会报错
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"您确认删除%@搜索历史",self.dataArray[indexPath.row]] preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *ok = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            switch (self.type) {
                case 0:{
                    [UserModel removeGoodsHistory:self.dataArray[indexPath.row]];
                    self.dataArray = [UserModel sharedInstanced].searchGoodsArray;
                    [self.tableView reloadData];
                    }break;
                case 1:{
                    [UserModel removeShopHistory:self.dataArray[indexPath.row]];
                    self.dataArray = [UserModel sharedInstanced].searchShopArray;
                    [self.tableView reloadData];
                }break;
            }

        }];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"123");
        }];
        [alertC addAction:ok];
        [alertC addAction:cancel];
        [self presentViewController:alertC animated:YES completion:nil];
    }];
    action1.backgroundColor = [UIColor redColor];
    
    return @[action1];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class])];
    cell.textLabel.text = self.dataArray[indexPath.row];
    cell.textLabel.font = DEF_FontSize_12;
    cell.separatorInset = UIEdgeInsetsZero;
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (self.type) {
        case 0:{
            [UserModel addSearchGoodsHistory:self.dataArray[indexPath.row]];
            SearchGoodsViewController *vc = [SearchGoodsViewController new];
            vc.name = self.dataArray[indexPath.row];
            [self.navigationController pushViewController:vc animated:YES];
        }break;
        case 1:{
            [UserModel addSearchShopHistory:self.dataArray[indexPath.row]];
            SearchShopViewController *vc = [SearchShopViewController new];
            vc.name = self.dataArray[indexPath.row];
            [self.navigationController pushViewController:vc animated:YES];
        }break;
    }
}

#pragma mark - set & get

- (UITableView *)tableView{
    if (!_tableView) {
        
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorInset = UIEdgeInsetsZero;
        if ([_tableView respondsToSelector:@selector(setLayoutMargins:)]) {
            [_tableView setLayoutMargins:UIEdgeInsetsZero];
        }
        _tableView.sectionFooterHeight = .01;
        _tableView.sectionHeaderHeight = .01;
        _tableView.rowHeight = 40;
        _tableView.tableFooterView = self.footerView;
        _tableView.tableHeaderView = self.headerView;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass([UITableViewCell class])];
    }
    return _tableView;
}

- (UIView *)headerView{
    if (!_headerView) {
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.01)];
    }
    return _headerView;
}

- (UIView *)footerView{
    if (!_footerView) {
        _footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.01)];
    }
    return _footerView;
}

- (NSDictionary *)dataDictionary{
    if (!_dataDictionary) {
        _dataDictionary = @{};
    }
    return _dataDictionary;
}

@end
